﻿using UnityEngine;

namespace Core.Audio
{
    [DisallowMultipleComponent]
    public class UIAudioPlayer : MonoBehaviour
    {
        public EGameEvent PlayEvent;
        public EGameEvent StopEvent;

        public string ResKey;
        private AudioObject audioObj;
        private AudioSystem sysAudio;
        private void Awake()
        {
            sysAudio = Context.Game.Get<AudioSystem>();
            audioObj = sysAudio.Pop();

            AddFMODEvent(PlayEvent);
            AddFMODEvent(StopEvent);
        }

        private void OnDestroy()
        {
            sysAudio.Push(audioObj);
            audioObj = null;
        }

        private void AddFMODEvent(EGameEvent gEvent)
        {
            if (AudioEvent.Dict.ContainsKey(gEvent))
            {
                gameObject.AddComponent(AudioEvent.Dict[PlayEvent]);
            }
            else if (gEvent != EGameEvent.None)
            {
                log.err($"没有该类型的触发 {gEvent}");
            }
        }

        public void HandleGameEvent(EGameEvent gameEvent)
        {
            if (PlayEvent == gameEvent)
            {
                Play();
            }
            if (StopEvent == gameEvent)
            {
                Stop();
            }
        }

        private void Play()
        {
            audioObj.SetRes(ResKey);
            audioObj.Start();
        }

        private void Stop()
        {
            audioObj.Stop();
        }
    }
}
